package com.azkj.album.view.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.azkj.album.MyApplication;
import com.azkj.album.R;
import com.azkj.album.adapter.ClassPhotoAdapter;
import com.azkj.album.dto.AddOrderBean;
import com.azkj.album.dto.BackGroundListBean;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.LoginBean;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.dto.NewGalleryBean;
import com.azkj.album.dto.NewPhotoBean;
import com.azkj.album.dto.VipInfoBean;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.utils.LogUtils;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.presenter.GetVIPInfoPresenter;
import com.azkj.album.presenter.NewPhotoPresenter;
import com.azkj.album.utils.GlideEngine;
import com.azkj.album.utils.ImageLoader;
import com.azkj.album.utils.Utils;
import com.azkj.album.view.base.BaseActivity;
import com.azkj.album.view.iview.INewPhotoView;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.basic.PictureSelectionModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectorConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.interfaces.OnSelectLimitTipsListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NewPhotoActivity extends BaseActivity implements INewPhotoView {
    @BindView(R.id.tv_photo_class_layout)
    RelativeLayout mPhotoClassLayout;
    @BindView(R.id.rv_class_photo_layout)
    RecyclerView mRvPhotoClass;
    @BindView(R.id.tv_photo_class)
    TextView mTvPhotoClass;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.nguytrds)
    View nguytrds;
    private NewPhotoPresenter mPresenter;
    private List<NewPhotoBean> mNewPhotoBeanList = new ArrayList<>();
    //选择器需要的名称
    private List<String> mClassBeanList = new ArrayList<>();
    private ClassPhotoAdapter classPhotoAdapter;
    private NewGalleryBean addData = new NewGalleryBean("add", "", 0);
    private ArrayList<NewGalleryBean> newGalleryBeans = new ArrayList<>();
    private ArrayList<String> images = new ArrayList<>();
    //新建图册选择的分类ID
    private Integer selectClassID = -1;
    private ListData mListData;
    private boolean isAddAndReducePic;

    private ArrayList<NewGalleryBean> newAddPic = new ArrayList<>();

    private boolean isVip = false;

    private int immediateUploadingCount = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_photo;
    }

    @Override
    public void initView() {
        newGalleryBeans.add(addData);
        classPhotoAdapter = new ClassPhotoAdapter(NewPhotoActivity.this, R.layout.activity_add_photo);
        mRvPhotoClass.setLayoutManager(new GridLayoutManager((Context) this, 4));
        mRvPhotoClass.addItemDecoration(new GridItemDecoration(this, 5));
        mRvPhotoClass.setAdapter(classPhotoAdapter);
        classPhotoAdapter.setNewData(newGalleryBeans);
        classPhotoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position + 1 == adapter.getData().size()) {
                mPresenter.getVip();
            } else {
                ArrayList<Object> photoPathList = new ArrayList<>();
                for (int i = 0; i < classPhotoAdapter.getData().size() - 1; i++) {
                    photoPathList.add(classPhotoAdapter.getData().get(i).getImgPath());
                }
                if (!photoPathList.isEmpty()) {
                    new XPopup.Builder(NewPhotoActivity.this)
                            .asImageViewer(view.findViewById(R.id.iv_image), position, photoPathList, true, false, -1, -1, -1, false, (popupView, position1) -> popupView.updateSrcView(mRvPhotoClass.getChildAt(position1).findViewById(R.id.iv_image)), new ImageLoader())
                            .show();
                }
            }
        });
    }

    @Override
    public void initData() {
        initIntent();
        mPresenter.classPhoto();
    }

    private void initIntent() {
        Intent intent = getIntent();
        isAddAndReducePic = intent.getBooleanExtra("isAddAndReducePic", false);
        mListData = (ListData) intent.getSerializableExtra("detail");
        if (isAddAndReducePic) {
            tvTitle.setText("编辑图册");
            nguytrds.setVisibility(View.GONE);
            tvConfirm.setVisibility(View.VISIBLE);
            if (mListData != null) {
                newGalleryBeans.clear();
                if (!TextUtils.isEmpty(mListData.getImages())) {
                    String[] split = mListData.getImages().split(",");
                    for (String s : split) {
                        newGalleryBeans.add(new NewGalleryBean(s, "", 0));
                    }
                }
                newGalleryBeans.add(addData);
                classPhotoAdapter.setNewData(newGalleryBeans);
                if (mListData.getAlbumcategory() != null) {
                    mTvPhotoClass.setText(mListData.getAlbumcategory().getName());
                    selectClassID = mListData.getAlbumcategory().getId();
                }
            }
        } else {
            mPresenter.getPreDetail();
        }
    }

    @OnClick({R.id.iv_back, R.id.tv_photo_class_layout, R.id.tv_new_photo_determine, R.id.tv_new_photo_next,
            R.id.tv_confirm})
    public void onClick(View v) {
        if (Utils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_photo_class_layout:
                OptionsPickerView<String> pickerView = new OptionsPickerBuilder(this, (options1, options2, options3, v1) -> {
                    // 处理选择结果
                    String result = mNewPhotoBeanList.get(options1).getName();
                    selectClassID = mNewPhotoBeanList.get(options1).getId();
                    mTvPhotoClass.setText(result);
                }).build();
                // 填充数据源
                pickerView.setPicker(mClassBeanList);
                pickerView.setSelectOptions(0);
                pickerView.show();
                break;
            case R.id.tv_new_photo_determine:
                if (selectClassID == -1) {
                    ToastUtils.showCenterToast("请选择图册类别");
                    return;
                }
                if (newGalleryBeans.size() < 2) {
                    ToastUtils.showCenterToast("请选择照片");
                    return;
                }
                //直接上传
                if (!newGalleryBeans.isEmpty()) {
                    String token = ConfigStorage.getInstance().getToken();
                    immediateUploadingCount = 0;
                    for (int i = 0; i < newGalleryBeans.size(); i++) {
                        NewGalleryBean bean = newGalleryBeans.get(i);
                        if (TextUtils.isEmpty(bean.getFullUrl()) && !"add".equals(bean.getImgPath())) {
                            mPresenter.UploadFile(token, bean, i, false, -1);
                        }
                    }
                }
                break;
            case R.id.tv_new_photo_next:
                if (selectClassID == -1) {
                    ToastUtils.showCenterToast("请选择图册类别");
                    return;
                }
                if (newGalleryBeans.size() < 2) {
                    ToastUtils.showCenterToast("请选择照片");
                    return;
                }
                Intent next = new Intent(NewPhotoActivity.this, NewPhotoSelectActivity.class);
                next.putExtra("gallerList", newGalleryBeans);
                next.putExtra("classID", selectClassID);
                // 携带type和detail
                next.putExtra("type", getIntent().getIntExtra("type", 1));
                next.putExtra("detail", getIntent().getSerializableExtra("detail"));
                startActivity(next);
                break;
            case R.id.tv_confirm:
                compile();
                break;
        }
    }

    private void compile() {
        if (!newAddPic.isEmpty()) {
            String token = ConfigStorage.getInstance().getToken();
            int saveCount = 0;
            for (int i = 0; i < newAddPic.size(); i++) {
                NewGalleryBean bean = newAddPic.get(i);
                saveCount++;
                if (TextUtils.isEmpty(bean.getFullUrl()) && !"add".equals(bean.getImgPath())) {
                    mPresenter.UploadFile(token, bean, i, true, saveCount);
                }
            }
        } else {
            newSaveAlbum();
        }
    }

    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_SAVE_SUCCESS:
                finish();
                break;
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new NewPhotoPresenter(this);
    }


    @Override
    public void classSuccess(List<NewPhotoBean> newPhotoBeans) {
        for (int i = 0; i < newPhotoBeans.size(); i++) {
            mClassBeanList.add(newPhotoBeans.get(i).getName());
        }
        mNewPhotoBeanList.addAll(newPhotoBeans);
    }

    @Override
    public void classFail(String msg) {

    }

    @Override
    public void uploadFileSuccess(int position, NewGalleryBean bean, boolean isCompile, int saveCount) {
        LogUtils.d(TAG + " uploadFileSuccess is " + bean.toString());

//        runOnUiThread(() -> {
        if (isCompile) {
            for (int i = 0; i < newGalleryBeans.size(); i++) {
                if (newGalleryBeans.get(i).getImgPath().equals(newAddPic.get(position).getImgPath())) {
                    newGalleryBeans.set(i, bean);
                    classPhotoAdapter.notifyItemChanged(i);
                }
            }
            if (mListData != null && newAddPic.size() == saveCount) {
                newSaveAlbum();
            }
        } else {
            newGalleryBeans.set(position, bean);
            classPhotoAdapter.notifyItemChanged(position);
            immediateUploadingCount++;
            if (immediateUploadingCount == newGalleryBeans.size() - 1) {
                newAddAlbum();
            }
        }

//        });

    }

    private void newSaveAlbum() {
        String token = ConfigStorage.getInstance().getToken();
        mPresenter.newSaveAlbum(
                token,
                String.valueOf(mListData.getId()),
                String.valueOf(selectClassID),
                String.valueOf(mListData.getBackgroundId()),
                mListData.getBackgroundImage(),
                String.valueOf(mListData.getMapId()),
                mListData.getMapImage(),
                getImages(),
                mListData.getChooseImages(),
                mListData.getIntro(),
                mListData.getCoverImage(),
                mListData.getRemark()
        );
    }

    /**
     * 新增时点击确定上传完成图片之后生成相册
     */
    private void newAddAlbum() {
        String token = ConfigStorage.getInstance().getToken();
        NewGalleryBean newGalleryBean = newGalleryBeans.get(0);
        StringBuilder urls = new StringBuilder();
        for (NewGalleryBean galleryBean : newGalleryBeans) {
            if (!galleryBean.getImgPath().equals("add")) {
                urls.append(galleryBean.getFullUrl()).append(",");
            }
        }
        if (urls.length() > 0) {
            urls.deleteCharAt(urls.length() - 1);
        }
        Log.d(TAG, "newAddAlbum: urls === " + urls);
        mPresenter.newSaveAlbum(
                token,
                "0",
                String.valueOf(selectClassID),
                "",
                "",
                "",
                "",
                urls.toString(),
                "",
                "",
                "",
                ""
        );
    }

    private String getImages() {
        StringBuilder images = new StringBuilder();
        for (NewGalleryBean newGalleryBean : newGalleryBeans) {
            if (!newGalleryBean.getImgPath().equals("add") &&
                    !TextUtils.isEmpty(newGalleryBean.getImgPath()) &&
                    TextUtils.isEmpty(newGalleryBean.getFullUrl())) {
                images.append(newGalleryBean.getImgPath()).append(",");
            }
        }
        if (!newAddPic.isEmpty()) {
            for (NewGalleryBean newGalleryBean : newAddPic) {
                if (!TextUtils.isEmpty(newGalleryBean.getFullUrl())) {
                    images.append(newGalleryBean.getFullUrl()).append(",");
                }
            }
        }
        if (images.length() > 0) {
            images.deleteCharAt(images.length() - 1);
        }
        return images.toString();
    }

    @Override
    public void uploadFileFail(String msg) {

    }

    @Override
    public void uploadProcess(int position, NewGalleryBean bean, boolean isCompile) {
        LogUtils.d(TAG + " progress is " + bean.getProgress());
        if (isCompile) {
            for (int i = 0; i < newGalleryBeans.size(); i++) {
                if (newGalleryBeans.get(i).getImgPath().equals(newAddPic.get(position).getImgPath())) {
                    newGalleryBeans.set(i, bean);
                }
            }
        } else {
            newGalleryBeans.set(position, bean);
        }
        runOnUiThread(() -> classPhotoAdapter.notifyItemChanged(position));
    }

    @Override
    public void newSaveSuccess(String stringSave) {
        Log.d(TAG, "newSaveSuccess: " + stringSave);
        if (isAddAndReducePic) {
            mListData.setImages(getImages());
            ListData.Albumcategory albumcategory = mListData.getAlbumcategory();
            mListData.setAlbumcategory(
                    new ListData.Albumcategory(albumcategory.getCreatetime(),
                            selectClassID, mTvPhotoClass.getText().toString(),
                            albumcategory.getOrderIndex(), albumcategory.getUpdatetime()));
            Intent intent = new Intent();
            intent.putExtra("detail", mListData);
            setResult(RESULT_OK, intent);
            finish();
        } else {
            finish();
        }
    }

    @Override
    public void newSaveFail(String msg) {
        ToastUtils.showCenterToast(msg);
    }

    @Override
    public void backGroundSuccess(List<NewPhotoBean> stringBackGround) {

    }

    @Override
    public void backGroundFail(String msg) {

    }

    @Override
    public void backGroundListSuccess(List<BackGroundListBean> stringBackGround) {

    }

    @Override
    public void backGroundListFail(String msg) {

    }

    @Override
    public void introSuccess(List<String> stringHistoryList) {

    }

    @Override
    public void introFail(String msg) {

    }

    @Override
    public void remarkSuccess(List<String> stringRemarkList) {

    }

    @Override
    public void remarkFail(String msg) {

    }

    @Override
    public void addOrderSuccess(AddOrderBean addOrderBeans) {

    }

    @Override
    public void addOrderFail(String msg) {

    }

    @Override
    public void getPerDetail(ListData listData) {
        ListData.Albumcategory albumcategory = listData.getAlbumcategory();
        if (albumcategory != null) {
            selectClassID = albumcategory.getId();
            if (!TextUtils.isEmpty(albumcategory.getName())) {
                mTvPhotoClass.setText(albumcategory.getName());
            } else {
                mTvPhotoClass.setText("请选择分类");
            }
        }
    }

    @Override
    public void getPerDetailFail(String msg) {

    }

    @Override
    public void VipSuccess(VipInfoBean vipInfoBean) {
        if (vipInfoBean != null && vipInfoBean.getIs_vip() == 1){
            isVip = true;
        }
        Log.d(TAG, "onItemClick: isVip ===== " + isVip);
        if (isVip){
            selectAlbum();
        }else {
            if (newGalleryBeans.size() - 1 == 10){
                showOpenDialog(false);
            }else {
                selectAlbum();
            }
        }

    }

    @Override
    public void VipFail(String error) {
        isVip = false;
        if (newGalleryBeans.size() - 1 == 10){
            showOpenDialog(false);
        } else {
            selectAlbum();
        }
    }

    @Override
    public void deleteIntroSuccess(String sString) {

    }

    @Override
    public void deleteIntroFail(String error) {

    }

    @Override
    public void deleteRemarkSuccess(String sString) {

    }

    @Override
    public void deleteRemarkFail(String error) {

    }

    private void showOpenDialog(boolean isFinishCur){
        new CommonDialog.Builder(MyApplication.getCurrentActivity())
                .setDesc("普通用户一个图册只能上传10张图片，\n如需上传更多图片请购买会员").setButton("取消", "确定").setBackground(R.mipmap.ic_login_error).setOnClickListener((dialog, confirm) -> {
                    if (confirm) {
                        Intent intent = new Intent(MyApplication.getCurrentActivity(), MemberActivity.class);
                        startActivity(intent);
                        if (isFinishCur){
                            MyApplication.getCurrentActivity().finish();
                        }
                    }
                    dialog.dismiss();
                }).show();
    }

    private void selectAlbum(){
        PictureSelectionModel model = PictureSelector.create(NewPhotoActivity.this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine());
        if (!isVip) {
            int size = newGalleryBeans.size() - 1;
            model.setMaxSelectNum(10 - size);
            model.setSelectLimitTipsListener((context, media, config, limitType) -> {
                showOpenDialog(true);
                return true;
            });
        } else {
            model.setMaxSelectNum(10000);
        }
        model.isPreviewImage(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        images.clear();
                        for (LocalMedia localMedia : result) {
                            images.add(localMedia.getRealPath());
                        }
//                                    images = data.getStringArrayListExtra(PhotoSelector.SELECT_RESULT);
                        newAddPic.clear();
                        newGalleryBeans.remove(addData);
                        NewGalleryBean bean;
                        if (null != images && !images.isEmpty()) {
                            for (String img : images) {
                                bean = new NewGalleryBean();
                                bean.setImgPath(img);
                                newGalleryBeans.add(bean);
                                newAddPic.add(bean);
                            }
                        }

                        newGalleryBeans.add(addData);
                        classPhotoAdapter.setNewData(newGalleryBeans);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }
}
